<?php
namespace App\Controller;

use Core\AbstractInterface\AbstractController;
use Core\Swoole\AsyncTaskManager;
use Core\Swoole\Server;
use App\Vendor\StringHelper;
use Conf\Config;
use App\Model\Users;
use App\Model\ChatNotice;
use App\Model\ChatGroup;
use App\Model\FriendRelation;
use App\Model\GroupRelation;
use App\Vendor\Redis;
use App\Vendor\Session;

class WebSocket extends AbstractController
{

    public function index(){
        if(!Session::has('loginInfo')){
            $userId = parent::request()->getRequestParam('userId');
            if(!empty($userId)){
                $userInfo=(new Users())->getUserInfoById($userId);
                if(!empty($userInfo)){
                    Session::set('loginInfo', json_encode($userInfo));
                    $this->logout($userInfo['userId']);
                }
            }
        }
        $this->response()->write(file_get_contents(ROOT."/App/View/client.html"));
    }

    public function getSession(){
        if(Session::has('loginInfo')){
            $data['isLogin']=1;
            $data['info']=json_decode(Session::find('loginInfo'),'true');
        }else{
            $data['isLogin']=0;
            $data['info']=(object)[];
        }
        $this->response()->writeJson(0,$data,"获取登录状态");
    }

    public function login(){
        $mobile = parent::request()->getRequestParam('mobile');
        $password = parent::request()->getRequestParam('password');
        $userInfo = (new Users())->userLogin($mobile,$password);
        if(!empty($userInfo) && $userId=$userInfo['userId']){
            Session::set('loginInfo', json_encode($userInfo));
            $this->logout($userInfo['userId']);
            $this->response()->writeJson(0,$userInfo,"登录成功");
        }else{
            $this->response()->writeJson(100,(object)[],'登录失败');
        }
    }
    
    public function register(){
        $mobile = parent::request()->getRequestParam('mobile');
        if((new Users())->getUserInfoByMobile($mobile)){
            $this->response()->writeJson(100,(object)[],'注册失败,手机号已存在');
        }else{
            $password = parent::request()->getRequestParam('password');
            $username = parent::request()->getRequestParam('username');
            $userInfo = (new Users())->userRegister($mobile,$username,$password);
            if(!empty($userInfo)){
                Session::set('loginInfo', json_encode($userInfo));
                $this->response()->writeJson(0,$userInfo,"注册成功");
            }else{
                $this->response()->writeJson(100,(object)[],'注册失败');
            }
        }
    }

    public function getPersonList(){
        $loginInfo=json_decode(Session::find('loginInfo'),'true');
        if(!$loginInfo || !$loginInfo['userId']){
            $this->response()->writeJson(200,[],'需要重新登录');
            return ;
        }
        $loginId = $loginInfo['userId'];
        $data = [];
        $friends = (new FriendRelation())->getFriendIdByUserId($loginId);
        if($friends){
            $conf = Config::getInstance()->getConf('REDISMAP');
            $redis = new Redis();
            $redis->hSet($conf['SWOOLE_USER_PERSON_LIST'],$loginId,json_encode($friends));
            foreach ($friends as $value){
                $info = $redis->hGet($conf['SWOOLE_USER_LIST'],$value);
                if(!$info){
                    $info = (new Users())->getUserInfoById($value);
                    if($info){
                        $info['onLine']=0;
                        $info['FD']=0;
                        $redis->hSet($conf['SWOOLE_USER_LIST'],$value,json_encode($info));
                        $info['msgNum']=0;
                    }
                }else{
                    $info = json_decode($info,true);
                    $redisKey=$value>$loginId?$loginId.$value:$value.$loginId;
                    $info['msgNum']=$redis->exist($conf['SWOOLE_CHAT_HISTORY_NUM'].$redisKey)?$redis->get($conf['SWOOLE_CHAT_HISTORY_NUM'].$redisKey):0;
                }
                if($info){
                    $data[]=$info;
                }
            }
        }else{
            $data = [];
        }
        $this->response()->writeJson(0,$data,"获取成功");
    }

    public function getGroupList(){
        $loginInfo=json_decode(Session::find('loginInfo'),'true');
        if(!$loginInfo || !$loginInfo['userId']){
            $this->response()->writeJson(200,[],'需要重新登录');
            return ;
        }
        $loginId = $loginInfo['userId'];
        $data = [];
        $groups = (new GroupRelation())->getGroupIdByUserId($loginId);
        if($groups){
            $conf = Config::getInstance()->getConf('REDISMAP');
            $redis = new Redis();
            $redis->hSet($conf['SWOOLE_USER_GROUP_LIST'],$loginId,json_encode($groups));
            foreach ($groups as $value){
                $info = $redis->hGet($conf['SWOOLE_GROUP_LIST'],$value);
                if(!$info){
                    $info = (new ChatGroup())->getGroupInfo($value);
                    if($info){
                        $redis->hSet($conf['SWOOLE_GROUP_LIST'],$value,json_encode($info));
                        $info['msgNum']=0;
                    }
                }else{
                    $info = json_decode($info,true);
                    $redisKey='group_'.($value>$loginId?$loginId.$value:$value.$loginId);
                    $info['msgNum']=$redis->exist($conf['SWOOLE_CHAT_HISTORY_NUM'].$redisKey)?$redis->get($conf['SWOOLE_CHAT_HISTORY_NUM'].$redisKey):0;
                }
                if($info){
                    if($info['owner_id']==$loginId){
                        $groupUser = (new GroupRelation())->getUserIdByGroupId($info['id']);
                        $info['groupUser']= ','.implode(',', $groupUser).',';
                    }else{
                        $info['groupUser']="";
                    }
                    $data[]=$info;
                }
            }
        }else{
            $data = [];
        }
        $this->response()->writeJson(0,$data,"获取成功");
    }

    public function getNoticeNum(){
        $loginInfo=json_decode(Session::find('loginInfo'),'true');
        if(!$loginInfo || !$loginInfo['userId']){
            $this->response()->writeJson(200,'','需要重新登录');
            return ;
        }
        $loginId = $loginInfo['userId'];
        $noticeNum = (new ChatNotice())->getNoticeNum($loginId);
        $this->response()->writeJson(0,$noticeNum,"获取成功");
    }

    public function getNoticeList(){
        $page = trim(parent::request()->getRequestParam('page'));
        $page=$page<=0?1:$page;
        $loginInfo=json_decode(Session::find('loginInfo'),'true');
        if(!$loginInfo || !$loginInfo['userId']){
            $this->response()->writeJson(200,[],'需要重新登录');
            return ;
        }
        $loginId = $loginInfo['userId'];
        $data = (new ChatNotice())->getAllNotice($loginId,$page);
        if (!$data){
            $this->response()->writeJson(0,[],"获取成功");
            return ;
        }else{
            $conf = Config::getInstance()->getConf('REDISMAP');
            $redis = new Redis();
            foreach ($data['users'] as &$value){
                if($value['noticeType']==1  || $value['noticeType']==2){
                    $sendInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$value['sendId']);
                    if(!$sendInfo){
                        $sendInfo = (new Users())->getUserInfoById($value['sendId']);
                        if($sendInfo){
                            $sendInfo['onLine']=0;
                            $sendInfo['FD']=0;
                            $redis->hSet($conf['SWOOLE_USER_LIST'],$value['sendId'],json_encode($sendInfo));
                            $value['sendInfo']=$sendInfo;
                        }
                    }else{
                        $sendInfo = json_decode($sendInfo,true);
                        $value['sendInfo']=$sendInfo;
                    }
                }else{
                    $sendInfo = $redis->hGet($conf['SWOOLE_GROUP_LIST'],$value['sendId']);
                    if(!$sendInfo){
                        $sendInfo = (new ChatGroup())->getGroupInfo($value['sendId']);
                        if($sendInfo){
                            $redis->hSet($conf['SWOOLE_USER_LIST'],$value['sendId'],json_encode($sendInfo));
                            $value['sendInfo']=$sendInfo;
                        }
                    }else{
                        $sendInfo = json_decode($sendInfo,true);
                        $value['sendInfo']=$sendInfo;
                    }
                }
                if($value['noticeType']==1 || $value['noticeType']==3){
                    $methodInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$value['methodId']);
                    if(!$methodInfo){
                        $methodInfo = (new Users())->getUserInfoById($value['methodId']);
                        if($methodInfo){
                            $methodInfo['onLine']=0;
                            $methodInfo['FD']=0;
                            $redis->hSet($conf['SWOOLE_USER_LIST'],$value['methodId'],json_encode($methodInfo));
                            $value['methodInfo']=$methodInfo;
                        }
                    }else{
                        $methodInfo = json_decode($methodInfo,true);
                        $value['methodInfo']=$methodInfo;
                    }
                }else{
                    $methodInfo = $redis->hGet($conf['SWOOLE_GROUP_LIST'],$value['methodId']);
                    if(!$methodInfo){
                        $methodInfo = (new ChatGroup())->getGroupInfo($value['methodId']);
                        if($methodInfo){
                            $redis->hSet($conf['SWOOLE_USER_LIST'],$value['methodId'],json_encode($methodInfo));
                            $value['methodInfo']=$methodInfo;
                        }
                    }else{
                        $methodInfo = json_decode($methodInfo,true);
                        $value['methodInfo']=$methodInfo;
                    }
                }
            }
            $this->response()->writeJson(0,$data,"获取成功");
            return ;
        }
    }

    public function talkOne($data){
        $sendId = $data['sendId'];
        $chatId = $data['chatId'];
        $conf = Config::getInstance()->getConf('REDISMAP');
        $redis = new Redis();
        $sendInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$sendId);
        $chatInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$chatId);
        if(!empty($sendInfo) || !empty($chatInfo)){
            $sendInfo=json_decode($sendInfo, TRUE);
            $chatInfo=json_decode($chatInfo, TRUE);

            $return = [];
            $retrun['type']='chat';
            $retrun['user']=$sendInfo;
            $retrun['content']=$data['content'];
            $retrun['chatFlag']=$sendId>$chatId?$chatId.$sendId:$sendId.$chatId;
            $retrun['chat']=$chatInfo;
            $retrun['time']=StringHelper::getDateTime(1);
            $retrun['status']=0;
            $keys = $redis->hKeys($conf['SWOOLE_CHAT_MESSAGE_LIST'].$retrun['chatFlag']);
            $key = $keys && is_array($keys)?max($keys)+1:0;
            $redis->hSet($conf['SWOOLE_CHAT_MESSAGE_LIST'].$retrun['chatFlag'], $key,json_encode($retrun));
            $historyNum = $redis->get($conf['SWOOLE_CHAT_HISTORY_NUM'].$retrun['chatFlag']);
            $newNum = $historyNum?$historyNum+1:1;
            $redis->set($conf['SWOOLE_CHAT_HISTORY_NUM'].$retrun['chatFlag'], $newNum);
            unset($retrun['status']);
            if($chatInfo['onLine']){
                Server::getInstance()->getServer()->push($chatInfo['FD'],json_encode($retrun));
            }

            $return = [];
            if($sendInfo['onLine']){
                $retrun['type']='chat';
                $retrun['user']=$sendInfo;
                $retrun['content']=$data['content'];
                $retrun['chatFlag']=$sendId>$chatId?$chatId.$sendId:$sendId.$chatId;
                $retrun['chat']=$chatInfo;
                $retrun['time']=StringHelper::getDateTime(1);
                Server::getInstance()->getServer()->push($sendInfo['FD'],json_encode($retrun));
                $return = [];
                if(!$chatInfo['onLine']){
                    $retrun['type']='chat';
                    $retrun['user']=$chatInfo;
                    $retrun['content']="一朝离去，相去甚远，待我归来，与君详谈。";
                    $retrun['chatFlag']=$sendId>$chatId?$chatId.$sendId:$sendId.$chatId;
                    $retrun['chat']=$sendInfo;
                    $retrun['time']=StringHelper::getDateTime(1);
                    Server::getInstance()->getServer()->push($sendInfo['FD'],json_encode($retrun));
                }
            }
        }
    }

    public function setMsgIsRead(){
        $userId = parent::request()->getRequestParam('userId');
        if(!$userId){
            $this->response()->writeJson(0,'','暂无可读信息');
            return ;
        }
        $loginInfo=json_decode(Session::find('loginInfo'),'true');
        if(!$loginInfo || !$loginInfo['userId']){
            $this->response()->writeJson(200,'','需要重新登录');
            return ;
        }
        $loginId = $loginInfo['userId'];
        $redis = new Redis();
        $conf = Config::getInstance()->getConf('REDISMAP');
        $redisKey=$userId>$loginId?$loginId.$userId:$userId.$loginId;
        $historyNum = $redis->get($conf['SWOOLE_CHAT_HISTORY_NUM'].$redisKey);
        if(!$historyNum || $historyNum<=0){
            $this->response()->writeJson(0,'','暂无可读信息');
            return ;
        }
        $msgList=$redis->hGetAll($conf['SWOOLE_CHAT_MESSAGE_LIST'].$redisKey);
        if(!$msgList){
            $this->response()->writeJson(0,'','暂无可读信息');
            return ;
        }
        $redis->set($conf['SWOOLE_CHAT_HISTORY_NUM'].$redisKey,0);
        krsort($msgList);
        foreach($msgList as $key=>$each){
            $each = json_decode($each,TRUE);
            if($each['status']==0){
                $each['status']=1;
                $redis->hSet($conf['SWOOLE_CHAT_MESSAGE_LIST'].$redisKey,$key,json_encode($each));
            }else{
                $this->response()->writeJson(0,'',"修改信息");
                return ;
            }
        }
    }

    public function getRecentMsg(){
        $userId = parent::request()->getRequestParam('userId');
        if(!$userId){
            $this->response()->writeJson(0,'','暂无可读信息');
            return ;
        }
        $loginInfo=json_decode(Session::find('loginInfo'),'true');
        if(!$loginInfo || !$loginInfo['userId']){
            $this->response()->writeJson(200,'','需要重新登录');
            return ;
        }

        $loginId = $loginInfo['userId'];
        $data = [];
        $redis = new Redis();
        $conf = Config::getInstance()->getConf('REDISMAP');
        $loginInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$loginId);
        if(!$loginInfo){
            $this->response()->writeJson(0,'','暂无可读信息');
            return ;
        }
        $loginInfo = json_decode($loginInfo,TRUE);
        $redisKey=$userId>$loginId?$loginId.$userId:$userId.$loginId;
        $keys=$redis->hKeys($conf['SWOOLE_CHAT_MESSAGE_LIST'].$redisKey);
        if(!$keys){
            $this->response()->writeJson(0,'','暂无可读信息');
            return ;
        }
        sort($keys);
        $keys = array_slice($keys,-10,10);
        $list = $redis->hMget($conf['SWOOLE_CHAT_MESSAGE_LIST'].$redisKey, $keys);
        foreach($list as $each){
            $each = json_decode($each,TRUE);
            unset($each['status']);
            Server::getInstance()->getServer()->push($loginInfo['FD'],json_encode($each));
        }
    }

    public function talkAll($data){
        $sendId = $data['sendId'];
        $groupId = $data['chatId'];
        $conf = Config::getInstance()->getConf('REDISMAP');
        $redis = new Redis();
        $sendInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$sendId);
        $groupMembers = (new GroupRelation())->getUserIdByGroupId($groupId);
        if(!empty($sendInfo) || !empty($groupMembers)){
            $sendInfo=json_decode($sendInfo, TRUE);
            $return = [];
            $retrun['type']='chat';
            $retrun['user']=$sendInfo;
            $retrun['content']=$data['content'];
            $retrun['chatFlag']="group".$groupId;
            $retrun['chat']=["groupId"=>$groupId];
            $retrun['time']=StringHelper::getDateTime(1);
            $keys = $redis->hKeys($conf['SWOOLE_CHAT_MESSAGE_LIST'].$retrun['chatFlag']);
            $key = $keys && is_array($keys)?max($keys)+1:0;
            $redis->hSet($conf['SWOOLE_CHAT_MESSAGE_LIST'].$retrun['chatFlag'], $key,json_encode($retrun));
            foreach ($groupMembers as $member){
                $memberInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$member);
                if(!empty($memberInfo)){
                    $memberInfo=json_decode($memberInfo, TRUE);
                    if($memberInfo['onLine']){
                        Server::getInstance()->getServer()->push($memberInfo['FD'],json_encode($retrun));
                    }
                }
            }
        }
    }

    public function getGroupRecentMsg(){
        $groupId = parent::request()->getRequestParam('groupId');
        if(!$groupId){
            $this->response()->writeJson(0,'','暂无可读信息');
            return ;
        }
        $loginInfo=json_decode(Session::find('loginInfo'),'true');
        if(!$loginInfo || !$loginInfo['userId']){
            $this->response()->writeJson(200,'','需要重新登录');
            return ;
        }

        $loginId = $loginInfo['userId'];
        $data = [];
        $redis = new Redis();
        $conf = Config::getInstance()->getConf('REDISMAP');
        $loginInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$loginId);
        if(!$loginInfo){
            $this->response()->writeJson(0,'','暂无可读信息');
            return ;
        }
        $loginInfo = json_decode($loginInfo,TRUE);
        $redisKey="group".$groupId;
        $keys=$redis->hKeys($conf['SWOOLE_CHAT_MESSAGE_LIST'].$redisKey);
        if(!$keys){
            $this->response()->writeJson(0,'','暂无可读信息');
            return ;
        }
        sort($keys);
        $keys = array_slice($keys,-10,10);
        $list = $redis->hMget($conf['SWOOLE_CHAT_MESSAGE_LIST'].$redisKey, $keys);
        foreach($list as $each){
            $each = json_decode($each,TRUE);
            Server::getInstance()->getServer()->push($loginInfo['FD'],json_encode($each));
        }
    }

    public function getGroupPerson(){
        $groupId = parent::request()->getRequestParam('groupId');
        if(!$groupId){
            $this->response()->writeJson(0,[],'暂无群组成员');
            return ;
        }
        $loginInfo=json_decode(Session::find('loginInfo'),'true');
        if(!$loginInfo || !$loginInfo['userId']){
            $this->response()->writeJson(200,[],'需要重新登录');
            return ;
        }
        $groupMembers = (new GroupRelation())->getUserIdByGroupId($groupId);
        if(!$groupMembers){
            $this->response()->writeJson(0,[],'暂无群组成员');
            return ;
        }
        $redis = new Redis();
        $conf = Config::getInstance()->getConf('REDISMAP');
        foreach ($groupMembers as $member){
            $memberInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$member);
            if(!$memberInfo){
                $memberInfo = (new Users())->getUserInfoById($member);
                if($memberInfo){
                    $memberInfo['onLine']=0;
                    $memberInfo['FD']=0;
                    $redis->hSet($conf['SWOOLE_USER_LIST'],$member,json_encode($memberInfo));
                }
            }else{
                $memberInfo = json_decode($memberInfo,true);
            }
            if($memberInfo){
                $data[]=$memberInfo;
            }
        }
        $this->response()->writeJson(0,$data,'获取群组成员');
    }

    public function searchUser(){
        $key = trim(parent::request()->getRequestParam('key'));
        $page = trim(parent::request()->getRequestParam('page'));
        if(!$key){
            $this->response()->writeJson(0,(object)[],'暂无搜索信息');
            return ;
        }
        $page=$page<=0?1:$page;
        $loginInfo=json_decode(Session::find('loginInfo'),'true');
        if(!$loginInfo || !$loginInfo['userId']){
            $this->response()->writeJson(200,(object)[],'需要重新登录');
            return ;
        }
        $loginId = $loginInfo['userId'];
        $conf = Config::getInstance()->getConf('REDISMAP');
        $redis = new Redis();
        $loginUserFriend = $redis->hGet($conf['SWOOLE_USER_PERSON_LIST'],$loginId);
        if(!$loginUserFriend){
            $loginUserFriend = [];
        }else{
            $loginUserFriend = json_decode($loginUserFriend, TRUE);
        }
        $loginUserFriend[]=$loginId;
        $list = (new Users())->searchUserByName($key,$loginUserFriend,$page);
        if(!$list){
            $this->response()->writeJson(0,(object)[],'暂无搜索信息');
        }else{
            $this->response()->writeJson(0,$list,'获取搜索信息');
        }
    }

    public function searchGroup(){
        $key = trim(parent::request()->getRequestParam('key'));
        $page = trim(parent::request()->getRequestParam('page'));
        if(!$key){
            $this->response()->writeJson(0,(object)[],'暂无搜索信息');
            return ;
        }
        $page=$page<=0?1:$page;
        $loginInfo=json_decode(Session::find('loginInfo'),'true');
        if(!$loginInfo || !$loginInfo['userId']){
            $this->response()->writeJson(200,(object)[],'需要重新登录');
            return ;
        }
        $loginId = $loginInfo['userId'];
        $conf = Config::getInstance()->getConf('REDISMAP');
        $redis = new Redis();
        $loginUserGroup = $redis->hGet($conf['SWOOLE_USER_GROUP_LIST'],$loginId);
        if(!$loginUserGroup){
            $loginUserGroup = [];
        }else{
            $loginUserGroup = json_decode($loginUserGroup, TRUE);
        }
        $list = (new ChatGroup())->searchGroupByName($key,$loginUserGroup,$page);
        if(!$list){
            $this->response()->writeJson(0,(object)[],'暂无搜索信息');
        }else{
            $this->response()->writeJson(0,$list,'获取搜索信息');
        }
    }

    public function addConnect(){
        $content = trim(parent::request()->getRequestParam('content'));
        $eventType = parent::request()->getRequestParam('eventType');
        $eventId = parent::request()->getRequestParam('eventId');
        if(!$eventId || !in_array($eventType, [1,2])){
            $this->response()->writeJson(300,'','提交申请失败');
        }
        $loginInfo=json_decode(Session::find('loginInfo'),'true');
        if(!$loginInfo || !$loginInfo['userId']){
            $this->response()->writeJson(200,'','需要重新登录');
            return ;
        }
        $loginId = $loginInfo['userId'];
        $conf = Config::getInstance()->getConf('REDISMAP');
        $redis = new Redis();
        $id = (new ChatNotice())->addNotice($loginId,$eventId,$eventType,$content);
        if($id){
            if($eventType==1){
                $eventInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$eventId);
                $chatFlag = 0;
                $chatContent = "请求加你为好友";
            }else{
                $groupInfo = (new ChatGroup())->getGroupInfo($eventId);
                $eventInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$groupInfo['owner_id']);
                $chatFlag = 11;
                $chatContent = "申请加入".$groupInfo['name'];
            }
            $loginInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$loginId);
            if(!empty($eventInfo) && !empty($loginInfo)){
                $loginInfo=json_decode($loginInfo, TRUE);
                $eventInfo=json_decode($eventInfo, TRUE);
                $notice = [];
                if($eventInfo['onLine']){
                    $notice['type']='notice';
                    $notice['user']=$loginInfo;
                    $notice['content']=$chatContent;
                    $notice['chatFlag']=$chatFlag;
                    $notice['chat']=(object)[];
                    $notice['time']=StringHelper::getDateTime(1);
                    Server::getInstance()->getServer()->push($eventInfo['FD'],json_encode($notice));
                }
            }
            $this->response()->writeJson(0,'','提交申请成功');
        }else{
            $this->response()->writeJson(300,'','提交申请失败');
        }
    }

    public function connectMethod(){
        $sendId = parent::request()->getRequestParam('sendId');
        $methodId = parent::request()->getRequestParam('methodId');
        $methodType = parent::request()->getRequestParam('methodType');
        $method = parent::request()->getRequestParam('method');
        if(!$sendId || !$methodId || !in_array($methodType, [1,2,3]) || !in_array($method, [0,1])){
            $this->response()->writeJson(300,'','操作失败');
            return ;
        }
        $loginInfo=json_decode(Session::find('loginInfo'),'true');
        if(!$loginInfo || !$loginInfo['userId']){
            $this->response()->writeJson(200,'','需要重新登录');
            return ;
        }
        $loginId = $loginInfo['userId'];
        $conf = Config::getInstance()->getConf('REDISMAP');
        $redis = new Redis();
        $id = (new ChatNotice())->editNotice($sendId,$methodId,$methodType,$method);
        if(!$id){
            $this->response()->writeJson(300,'','操作失败');
            return ;
        }
        if($methodType == 1){
            if($loginId!=$methodId){
                $this->response()->writeJson(300,'','操作失败');
                return ;
            }
            if($method==0){
                $msg = '已拒绝对方的好友申请';
                $fdMsg = '已拒绝了您的好友申请';
                $chatFlag = 2;
            }else{
                $msg = '已通过对方的好友申请';
                $fdMsg = '已通过了您的好友申请';
                $chatFlag = 1;
                $loginUserFriend = $redis->hGet($conf['SWOOLE_USER_PERSON_LIST'],$sendId);
                if(!$loginUserFriend){
                    $loginUserFriend = [];
                }else{
                    $loginUserFriend = json_decode($loginUserFriend, TRUE);
                }
                $loginUserFriend[]=$methodId;
                $redis->hSet($conf['SWOOLE_USER_PERSON_LIST'],$sendId, json_encode($loginUserFriend));

                $methodUserFriend = $redis->hGet($conf['SWOOLE_USER_PERSON_LIST'],$methodId);
                if(!$methodUserFriend){
                    $methodUserFriend = [];
                }else{
                    $methodUserFriend = json_decode($methodUserFriend, TRUE);
                }
                $methodUserFriend[]=$sendId;
                $redis->hSet($conf['SWOOLE_USER_PERSON_LIST'],$methodId, json_encode($methodUserFriend));
            }
            $sendInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$sendId);
            $sendInfo=json_decode($sendInfo, TRUE);
            $methodInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$methodId);
            $methodInfo=json_decode($methodInfo, TRUE);
        }elseif($methodType==2){
            if($method==0){
                $msg = '已拒绝对方的加群申请';
                $fdMsg = '已拒绝了您的加群申请';
                $chatFlag = 12;
            }else{
                $msg = '已通过对方的加群申请';
                $fdMsg = '已通过了您的加群申请';
                $chatFlag = 11;
                $loginUserGroup = $redis->hGet($conf['SWOOLE_USER_GROUP_LIST'],$methodId);
                if(!$loginUserGroup){
                    $loginUserGroup = [];
                }else{
                    $loginUserGroup = json_decode($loginUserGroup, TRUE);
                }
                $loginUserGroup[]=$sendId;
                $redis->hSet($conf['SWOOLE_USER_GROUP_LIST'],$methodId, json_encode($loginUserGroup));
            }
            $sendInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$sendId);
            $sendInfo=json_decode($sendInfo, TRUE);
            $groupInfo = (new ChatGroup())->getGroupInfo($methodId);
            $methodInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$groupInfo['owner_id']);
            $methodInfo=json_decode($methodInfo, TRUE);
            $methodInfo = array_merge($groupInfo,$methodInfo);
        }else{
            if($method==0){
                $msg = '已拒绝对方的加群邀请';
                $fdMsg = '已拒绝了您的加群邀请';
                $chatFlag = 7;
            }else{
                $msg = '已通过对方的加群邀请';
                $fdMsg = '已通过了您的加群邀请';
                $chatFlag = 6;
                $loginUserGroup = $redis->hGet($conf['SWOOLE_USER_GROUP_LIST'],$sendId);
                if(!$loginUserGroup){
                    $loginUserGroup = [];
                }else{
                    $loginUserGroup = json_decode($loginUserGroup, TRUE);
                }
                $loginUserGroup[]=$methodId;
                $redis->hSet($conf['SWOOLE_USER_GROUP_LIST'],$sendId, json_encode($loginUserGroup));
            }
            $groupInfo = (new ChatGroup())->getGroupInfo($sendId);
            $sendInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$groupInfo['owner_id']);
            $sendInfo=json_decode($sendInfo, TRUE);
            $sendInfo = array_merge($groupInfo,$sendInfo);
            $methodInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$methodId);
            $methodInfo=json_decode($methodInfo, TRUE);
        }

        if(!empty($methodInfo) && !empty($sendInfo)){
            $notice = [];
            if($methodInfo['onLine']){
                $notice['type']='notice';
                $notice['user']=$sendInfo;
                $notice['user']['msgNum']=0;
                $notice['content']=$msg;
                $notice['chatFlag']=$chatFlag+2;
                $notice['chat']=$methodInfo;
                $notice['time']=StringHelper::getDateTime(1);
                Server::getInstance()->getServer()->push($methodInfo['FD'],json_encode($notice));
            }
            if($sendInfo['onLine']){
                $notice['type']='notice';
                $notice['user']=$sendInfo;
                $notice['user']['msgNum']=0;
                $notice['content']=$fdMsg;
                $notice['chatFlag']=$chatFlag;
                $notice['chat']=$methodInfo;
                $notice['time']=StringHelper::getDateTime(1);
                Server::getInstance()->getServer()->push($sendInfo['FD'],json_encode($notice));
            }
        }
        $this->response()->writeJson(0,'',$msg);
    }

    public function saveGroupInfo(){
        $loginInfo=json_decode(Session::find('loginInfo'),'true');
        if(!$loginInfo || !$loginInfo['userId']){
            $this->response()->writeJson(200,(object)[],'需要重新登录');
            return ;
        }
        $loginId = $loginInfo['userId'];
        $chooseUid = parent::request()->getRequestParam('chooseUid');
        $groupId = parent::request()->getRequestParam('groupId');
        $groupName = parent::request()->getRequestParam('groupName');
        if($groupId>0){
            $groupInfo = (new ChatGroup ())->getGroupInfo($groupId);
        }
        if($groupId==0 || empty($groupInfo)){
            $groupId = (new ChatGroup ())->addChatGroup($loginId,$groupName);
            if(!$groupId){
                $this->response()->writeJson(300,(object)[],'操作失败');
                return ;
            }
        }else{
            if($groupInfo['owner_id'] != $loginId){
                $this->response()->writeJson(300,(object)[],'操作失败');
                return ;
            }
            if($groupInfo['name'] != $groupName){
                $groupId = (new ChatGroup ())->editChatGroup($groupInfo['id'],$groupName);
                if(!$groupId){
                    $this->response()->writeJson(300,(object)[],'操作失败');
                    return ;
                }
            }
        }
        unset($groupInfo);
        $groupInfo['id']=$groupId;
        $groupInfo['name']=$groupName;
        $groupInfo['owner_id']=$loginId;
        $chooseUid = explode(',',trim($chooseUid,','));
        if($chooseUid && count($chooseUid)>0){
            AsyncTaskManager::getInstance()->add(
                function () use($chooseUid,$groupInfo){
                    $conf = Config::getInstance()->getConf('REDISMAP');
                    $redis = new Redis();
                    $ownerInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$groupInfo['owner_id']);
                    $redis->hSet($conf['SWOOLE_GROUP_LIST'],$groupInfo['id'],json_encode($groupInfo));
                    foreach ($chooseUid as $uid){
                        $info = $redis->hGet($conf['SWOOLE_USER_LIST'],$uid);
                        if(!$info){
                            $info = (new Users())->getUserInfoById($uid);
                            if($info){
                                $info['onLine']=0;
                                $info['FD']=0;
                                $redis->hSet($conf['SWOOLE_USER_LIST'],$uid,json_encode($info));
                                (new ChatNotice())->addNotice($groupInfo['id'],$uid,3,'邀请您加入群聊');
                            }
                        }else{
                            $info = json_decode($info,true);
                            if($info['onLine']){
                                $notice['type']='notice';
                                $notice['user']= json_decode($ownerInfo);
                                $notice['content']='邀请你加入 '.$groupInfo['name'].' 一起聊天';
                                $notice['chatFlag']=6;
                                $notice['chat']=(object)[];
                                $notice['time']=StringHelper::getDateTime(1);
                                Server::getInstance()->getServer()->push($info['FD'],json_encode($notice));
                            }
                            (new ChatNotice())->addNotice($groupInfo['id'],$uid,3,'邀请您加入群聊');
                        }
                    }
                }
            );
        }
        $this->response()->writeJson(0,$groupInfo,'保存成功');
    }

    public function delPerson(){
        $methodId = parent::request()->getRequestParam('methodId');
        if(!$methodId){
            $this->response()->writeJson(300,'','操作失败');
        }
        $loginInfo=json_decode(Session::find('loginInfo'),'true');
        if(!$loginInfo || !$loginInfo['userId']){
            $this->response()->writeJson(200,'','需要重新登录');
            return ;
        }
        $loginId = $loginInfo['userId'];
        $id = (new FriendRelation())->delFriend($loginId, $methodId);
        if(!$id){
            $this->response()->writeJson(300,'','操作失败');
            return ;
        }
        $conf = Config::getInstance()->getConf('REDISMAP');
        $redis = new Redis();
        $loginUserFriend = $redis->hGet($conf['SWOOLE_USER_PERSON_LIST'],$loginId);
        if(!$loginUserFriend){
            $loginUserFriend = [];
        }else{
            $loginUserFriend = json_decode($loginUserFriend, TRUE);
            $flipLoginUserFriend = array_flip($loginUserFriend);
            unset($flipLoginUserFriend[$methodId]);
            $loginUserFriend=array_flip($flipLoginUserFriend);
        }
        $redis->hSet($conf['SWOOLE_USER_PERSON_LIST'],$loginId, json_encode($loginUserFriend));
        $methodUserFriend = $redis->hGet($conf['SWOOLE_USER_PERSON_LIST'],$methodId);
        if(!$methodUserFriend){
            $methodUserFriend = [];
        }else{
            $methodUserFriend = json_decode($methodUserFriend, TRUE);
            $flipMethodUserFriend = array_flip($methodUserFriend);
            unset($flipMethodUserFriend[$loginId]);
            $methodUserFriend=array_flip($flipMethodUserFriend);
        }
        $redis->hSet($conf['SWOOLE_USER_PERSON_LIST'],$methodId, json_encode($methodUserFriend));
        $loginInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$loginId);
        $methodInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$methodId);
        if(!empty($methodInfo) && !empty($loginInfo)){
            $loginInfo=json_decode($loginInfo, TRUE);
            $methodInfo=json_decode($methodInfo, TRUE);
            $notice = [];
            if($methodInfo['onLine']){
                $notice['type']='notice';
                $notice['user']=$loginInfo;
                $notice['content']='已删除该好友';
                $notice['chatFlag']=15;
                $notice['chat']=(object)[];
                $notice['time']=StringHelper::getDateTime(1);
                Server::getInstance()->getServer()->push($methodInfo['FD'],json_encode($notice));
            }
            if($loginInfo['onLine']){
                $notice['type']='notice';
                $notice['user']=$methodInfo;
                $notice['content']='已删除该好友';
                $notice['chatFlag']=15;
                $notice['chat']=(object)[];
                $notice['time']=StringHelper::getDateTime(1);
                Server::getInstance()->getServer()->push($loginInfo['FD'],json_encode($notice));
            }
        }
        $this->response()->writeJson(0,'','已删除该好友');
    }

    public function leaveGroup(){
        $methodId = parent::request()->getRequestParam('methodId');
        if(!$methodId){
            $this->response()->writeJson(300,'','操作失败');
        }
        $loginInfo=json_decode(Session::find('loginInfo'),'true');
        if(!$loginInfo || !$loginInfo['userId']){
            $this->response()->writeJson(200,'','需要重新登录');
            return ;
        }
        $loginId = $loginInfo['userId'];
        $id = (new GroupRelation())->userLeaveGroup($loginId, $methodId);
        if(!$id){
            $this->response()->writeJson(300,'','操作失败');
            return ;
        }
        $conf = Config::getInstance()->getConf('REDISMAP');
        $redis = new Redis();
        $loginUserGroup = $redis->hGet($conf['SWOOLE_USER_GROUP_LIST'],$loginId);
        if(!$loginUserGroup){
            $loginUserGroup = [];
        }else{
            $loginUserGroup = json_decode($loginUserGroup, TRUE);
            $flipLoginUserGroup = array_flip($loginUserGroup);
            unset($flipLoginUserGroup[$methodId]);
            $loginUserGroup=array_flip($flipLoginUserGroup);
        }
        $redis->hSet($conf['SWOOLE_USER_GROUP_LIST'],$loginId, json_encode($loginUserGroup));

        $groupMembers = (new GroupRelation())->getUserIdByGroupId($methodId);
        if(!empty($groupMembers)){
            AsyncTaskManager::getInstance()->add(
                function () use($groupMembers,$loginId,$methodId){
                    $conf = Config::getInstance()->getConf('REDISMAP');
                    $redis = new Redis();
                    $loginInfo = $redis->hGet($conf['SWOOLE_USER_LIST'],$loginId);
                    foreach ($groupMembers as $uid){
                        $info = $redis->hGet($conf['SWOOLE_USER_LIST'],$uid);
                        if(!empty($info)){
                            $info = json_decode($info,true);
                            if($info['onLine']){
                                $notice['type']='notice';
                                $notice['user']= json_decode($loginInfo,TRUE);
                                $notice['content']='退出了群聊';
                                $notice['chatFlag']=16;
                                $notice['chat']=["groupId"=>$methodId];
                                $notice['time']=StringHelper::getDateTime(1);
                                Server::getInstance()->getServer()->push($info['FD'],json_encode($notice));
                            }
                        }
                    }
                }
            );
        }
        $this->response()->writeJson(0,'','已退出该群组');
    }

    public function unsetGroup(){
        $groupId = parent::request()->getRequestParam('groupId');
        if(!$groupId){
            $this->response()->writeJson(300,'','操作失败');
        }
        $loginInfo=json_decode(Session::find('loginInfo'),'true');
        if(!$loginInfo || !$loginInfo['userId']){
            $this->response()->writeJson(200,'','需要重新登录');
            return ;
        }
        $loginId = $loginInfo['userId'];
        $groupInfo = (new ChatGroup ())->getGroupInfo($groupId);
        if($groupInfo['owner_id'] != $loginId){
            $this->response()->writeJson(300,(object)[],'操作失败');
            return ;
        }
        (new ChatGroup ())->unsetChatGroup($groupId);
        $groupMembers = (new GroupRelation())->getUserIdByGroupId($groupId);
        if(!empty($groupMembers)){
            AsyncTaskManager::getInstance()->add(
                function () use($groupMembers,$groupId){
                    $conf = Config::getInstance()->getConf('REDISMAP');
                    $redis = new Redis();
                    foreach ($groupMembers as $uid){
                        $redis->hDel($conf['SWOOLE_GROUP_LIST'],$groupId);
                        (new GroupRelation())->userLeaveGroup($uid, $groupId);
                        $loginUserGroup = $redis->hGet($conf['SWOOLE_USER_GROUP_LIST'],$uid);
                        if(!$loginUserGroup){
                            $loginUserGroup = [];
                        }else{
                            $loginUserGroup = json_decode($loginUserGroup, TRUE);
                            $flipLoginUserGroup = array_flip($loginUserGroup);
                            unset($flipLoginUserGroup[$groupId]);
                            $loginUserGroup=array_flip($flipLoginUserGroup);
                        }
                        $redis->hSet($conf['SWOOLE_USER_GROUP_LIST'],$uid, json_encode($loginUserGroup));
                        $info = $redis->hGet($conf['SWOOLE_USER_LIST'],$uid);
                        if(!empty($info)){
                            $info = json_decode($info,true);
                            if($info['onLine']){
                                $notice['type']='notice';
                                $notice['user']= (object)[];
                                $notice['content']='群聊已解散';
                                $notice['chatFlag']=17;
                                $notice['chat']=["groupId"=>$groupId];
                                $notice['time']=StringHelper::getDateTime(1);
                                Server::getInstance()->getServer()->push($info['FD'],json_encode($notice));
                            }
                        }
                    }
                }
            );
        }
        $this->response()->writeJson(0,'','群聊已解散');
    }

    public function logout($userId=0){
        if($userId>0){
            $conf = Config::getInstance()->getConf('REDISMAP');
            $redis = new Redis();
            $info = $redis->hGet($conf['SWOOLE_USER_LIST'],$userId);
            if(!empty($info)){
                $info = json_decode($info,true);
                if($info['onLine']){
                    $notice['type']='replace';
                    $notice['user']=(object)[];
                    $notice['content']='';
                    $notice['chatFlag']='1';
                    $notice['chat']=(object)[];
                    $notice['time']=StringHelper::getDateTime(1);
                    Server::getInstance()->getServer()->push($info['FD'],json_encode($notice));
                }
            }
        } else {
            $loginInfo=json_decode(Session::find('loginInfo'),'true');
            if(!$loginInfo || !$loginInfo['userId']){
                $this->response()->writeJson(0,'','已成功退出');
                return ;
            }
            Session::delete('loginInfo');
            $this->response()->writeJson(0,'','已成功退出');
        }
    }

    public function actionNotFound($actionName = null, $arguments = null) {}

    public function afterAction() {}

    public function onRequest($actionName) {}

    public function userList(){
        $conf = Config::getInstance()->getConf('REDISMAP');
        $redis = new Redis();
        $list = $redis->hGetAll($conf['SWOOLE_USER_LIST']);
        if(!empty($list)){
            foreach ($list as $fd=>$info){
                if(!$info){
                    unset($list[$fd]);
                }else{
                    $list[$fd] = json_decode($info, TRUE);
                }
            }
        }
        $this->response()->writeJson(200,$list,"this is all websocket list");
    }

    public function msgList(){
        $conf = Config::getInstance()->getConf('REDISMAP');
        $redis = new Redis();
        $list = $redis->hGetAll($conf['SWOOLE_CHAT_MESSAGE_LIST'].'group27');
        if(!empty($list)){
            foreach ($list as $fd=>&$info){
                if(!$info){
                    unset($list[$fd]);
                }else{
                    $info = json_decode($info, TRUE);
                }
            }
        }
        $this->response()->writeJson(200,$list,"this is all websocket list");
    }

    public function clear(){
        (new Redis())->rmBatch('swoole_');
    }
}
